package com.gupaoedu.design.proxy.custom;

import java.io.*;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2018/3/12.
 */
public class GPClassLoader extends ClassLoader{
    private File classPathFile = null;

    public GPClassLoader() {
        this.classPathFile = new File(GPClassLoader.class.getResource("").getPath());
    }

    @Override
    protected Class<?> findClass(String name){
        String className = GPClassLoader.class.getPackage().getName() + "." + name;
        if (null != classPathFile) {
            File classFile = new File(this.classPathFile, name.replaceAll("\\.", "/")+".class");
            if (classFile.exists()) {
                FileInputStream in = null;
                ByteArrayOutputStream out = null;

                try {
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int len ;
                    while ((len = in.read(buff)) != -1) {
                        out.write(buff,0,len);
                    }
                    return defineClass(className, out.toByteArray(), 0, out.size());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (null != in) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null != out) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
}
